/* 
 * File:   Server.h
 * Author: faraj
 *
 * Created on October 3, 2009, 5:19 AM
 */

#include "Client.h"


#ifndef _SERVER_H
#define	_SERVER_H

#include "../CTools/CTools.h"
#include "ClientList.h"
#include "ServerService.h"
#include "GlobalData.h"

static void runServer()
{    
    CServerSocket serverSock(CONTROL_PORT);
       
    cout << "File server starting....\t\t[DONE]" <<endl;
    
    while(true)
    {
        cout << " Listening on port " << CONTROL_PORT << endl;
        
        CSocket *sock = serverSock.accept();
        
        Client *cli = new Client(sock);
        
        bool success = false;
        
        Pthread_mutex_lock(&mutex_clientList);
            success = clientList.setClient(cli);
        Pthread_mutex_unlock(&mutex_clientList);
        
        if(success)
        {
            cout << "  Connection established from "
                << *(sock->getAddress()->getAddress()) << " on port "
                << (sock->getAddress()->getPort()) << endl;
            
            Pthread_create(cli->getThreadID(),NULL,ServerService,cli);
        }
        else
        {
            cout << "  Connection dropped from "
                << *(sock->getAddress()->getAddress()) << " on port "
                << (sock->getAddress()->getPort()) << endl;
            cli->close("error : server overloaded.. try again later..");
        }
    }
}

#endif	/* _SERVER_H */

